/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2023 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "adc.h"
#include "dma.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"
#include "rs485.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "stdio.h"
#include <stdlib.h>
#include "string.h"

/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
#define KP 15 //比例
#define KI 0.8  //积分

#define num_motors 4  //pwm输出个数、

float motor_max =  4.71 ;     //节气门全开电压（常闭节气门）
float motor_min = 0.51  ;    //节气门全闭电压（常闭节气门）
float errThreshold = 1; // 设置适当的阈值
int errCount1 = 0; // 计数1
float errCount2 = 0; // 计数2

//volatile uint16_t ADC_Value[8] = {0};  //AD采样保存数组
 uint16_t ADC_Value_1[8];
 uint16_t ADC_Value_3[8];
 uint16_t adc_temp_1[8];
 float adc_temp_3[8];
 uint8_t RxBuffer;

typedef struct
{
    float SetOpen;
    float err;
    float prevErr;
    float ActualOpen;
    float result;
    float integral;
} PIDController;

typedef struct
{
    PIDController pid; 
    uint32_t PWM_Channel;    
} MotorController;
	
  MotorController Motor[num_motors];

void PID_Init(PIDController *pid)
{
    pid->SetOpen =0;
    pid->err = 0;
    pid->prevErr = 0;
    pid->ActualOpen = 0;
    pid->result = 0;
    pid->integral = 0;
}

void SystemClock_Config(void);

//  PID控制器
void PID_Control(PIDController *pid, uint32_t PWM_Channel, int r)
{	
	pid->ActualOpen = 100/(motor_max-motor_min) * (((ADC_Value_3[r] * 3.3 / 65536) / 0.6) - motor_min);//将分压后的模拟电压转换回去，进行线性插值
		
  if(pid->SetOpen==0){
	    pid->err = pid->SetOpen - pid->ActualOpen + 0.2;
	  }

	else {
		  pid->err = pid->SetOpen - pid->ActualOpen;
	  }	
	
  if (pid->err > 20 ) {
    pid->integral = pid->integral - 60;
  }
  if (pid->err < -20) {
    pid->integral = pid->integral + 84;
  }

  else {
		pid->integral=pid->integral;
	}
	
  pid->integral += pid->err; //误差记录

  if (pid->integral > 2375){
    pid->integral = 2375;
	}
  else if (pid->integral < -1875){
    pid->integral = -1875; //防止积分饱和
	}

  pid->result = KP *pid->err + KI * pid->integral ;  //PI计算公式

  if (pid->result < 0){
    pid->result = 0;
	}
  else if (pid->result > 400){
    pid->result = 400;
	}

  __HAL_TIM_SET_COMPARE(&htim1, PWM_Channel, pid->result);
			
	
  if(fabs(pid->err -pid->prevErr) < errThreshold && pid->SetOpen==100 && errCount2 > 3){
		HAL_GPIO_WritePin(GPIOD,GPIO_PIN_0,GPIO_PIN_SET);
	if(errCount1 ==0){
			
			motor_max = (ADC_Value_3[r] * 3.3 / 65536) / 0.6;
			
		  errCount1	=1;
		}
		
	}
	
	pid->prevErr = pid->err;
	errCount2 = errCount2 + 0.01;
				
	RS485_Set_SendMode();
	printf("open%d=%.2f\r\n",r+1,pid->ActualOpen);
	RS485_Set_RecMode();
}

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* 串口中断回调函数 */
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
    if (huart == &huart1)
    {
        static uint8_t rx_index = 0;
        static char rx_buffer[50] = {0}; // 存储接收的字符
        static int received_data[4] = {0}; // 存储解析后的整数

        if (rx_index < sizeof(rx_buffer) - 1)
        {
            if (RxBuffer != '\r' && RxBuffer != '\n')
            {
                rx_buffer[rx_index++] = RxBuffer;
            }
            else
            {
                // 接收到回车或换行字符，说明一组数据已接收完毕
                rx_buffer[rx_index] = '\0'; // 添加字符串终止符

                // 解析字符串中的整数
                char *token = strtok(rx_buffer, " "); // 使用空格作为分隔符
                int i = 0;
                while (token != NULL && i < 4)
                {
                    received_data[i++] = atoi(token);
                    token = strtok(NULL, " ");
                }

                // 在这里，received_data 数组中包含了四个整数，可以进一步处理
                // 例如，将其赋值给电机控制器
                Motor[0].pid.SetOpen = received_data[0];
                Motor[1].pid.SetOpen = received_data[1];
                Motor[2].pid.SetOpen = received_data[2];
                Motor[3].pid.SetOpen = received_data[3];

                // 重置接收相关变量
                rx_index = 0;
                memset(rx_buffer, 0, sizeof(rx_buffer));
            }
        }

        // 继续接收下一个字符
        HAL_UART_Receive_IT(&huart1, &RxBuffer, 1);
    }
}


/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
void PeriphCommonClock_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
void motor_control(void)
{
	 for(int n=0;n<num_motors;n++)  
	    {
		     PID_Control(&Motor[n].pid, Motor[n].PWM_Channel,n);
      } 
//	   PID_Control(&Motor[1].pid, Motor[1].PWM_Channel,1);
}
/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

/* Configure the peripherals common clocks */
  PeriphCommonClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_DMA_Init();
  MX_USART1_UART_Init();
  MX_ADC3_Init();
  MX_TIM1_Init();
  MX_ADC1_Init();
	HAL_UART_Receive_IT(&huart1, (uint8_t *)&RxBuffer, 1);
  /* USER CODE BEGIN 2 */
//  char sendData[50];
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
	 for (int m = 0; m < num_motors; m++)
    {
        PID_Init(&Motor[m].pid);
    }
    Motor[0].PWM_Channel = TIM_CHANNEL_1;
    Motor[1].PWM_Channel = TIM_CHANNEL_2;
    Motor[2].PWM_Channel = TIM_CHANNEL_3;
    Motor[3].PWM_Channel = TIM_CHANNEL_4;
		
	HAL_ADCEx_Calibration_Start(&hadc3,ADC_CALIB_OFFSET,ADC_SINGLE_ENDED); //ADC校准
	HAL_ADCEx_Calibration_Start(&hadc1,ADC_CALIB_OFFSET,ADC_SINGLE_ENDED); //ADC校准
	
  HAL_ADC_Start_DMA(&hadc3, (uint32_t *)ADC_Value_3, 4); //打开DMA
	HAL_Delay(10);
	HAL_ADC_Start_DMA(&hadc1, (uint32_t *)ADC_Value_1, 8); //打开DMA
  HAL_Delay(10);
  HAL_TIM_PWM_Start(&htim1, TIM_CHANNEL_1);
  HAL_TIM_PWM_Start(&htim1, TIM_CHANNEL_2);
  HAL_TIM_PWM_Start(&htim1, TIM_CHANNEL_3);
  HAL_TIM_PWM_Start(&htim1, TIM_CHANNEL_4);
	
  while (1)
  {
    /* USER CODE END WHILE */
//    for (int i = 0; i < 8; ++i)
//    {
//      adc_temp_1[i] = ADC_Value_1[i]*55000/65536;
//    }
//		    for (int i = 0; i < 4; ++i)
//    {
//      adc_temp_3[i] = 100/(4.55-0.4) * ((ADC_Value_3[i]*5.5/65536 / 0.6) - 0.4);
////			adc_temp_3[i] = ADC_Value_3[i]*55000/65536;
//    }
    
    motor_control();

		HAL_Delay(30);
    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Supply configuration update enable
  */
  HAL_PWREx_ConfigSupply(PWR_LDO_SUPPLY);

  /** Configure the main internal regulator output voltage
  */
  __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);

  while(!__HAL_PWR_GET_FLAG(PWR_FLAG_VOSRDY)) {}

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI|RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.HSIState = RCC_HSI_DIV1;
  RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLM = 5;
  RCC_OscInitStruct.PLL.PLLN = 160;
  RCC_OscInitStruct.PLL.PLLP = 2;
  RCC_OscInitStruct.PLL.PLLQ = 2;
  RCC_OscInitStruct.PLL.PLLR = 2;
  RCC_OscInitStruct.PLL.PLLRGE = RCC_PLL1VCIRANGE_2;
  RCC_OscInitStruct.PLL.PLLVCOSEL = RCC_PLL1VCOWIDE;
  RCC_OscInitStruct.PLL.PLLFRACN = 0;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2
                              |RCC_CLOCKTYPE_D3PCLK1|RCC_CLOCKTYPE_D1PCLK1;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.SYSCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB3CLKDivider = RCC_APB3_DIV2;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_APB1_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_APB2_DIV2;
  RCC_ClkInitStruct.APB4CLKDivider = RCC_APB4_DIV2;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  {
    Error_Handler();
  }
}

/**
  * @brief Peripherals Common Clock Configuration
  * @retval None
  */
void PeriphCommonClock_Config(void)
{
  RCC_PeriphCLKInitTypeDef PeriphClkInitStruct = {0};

  /** Initializes the peripherals clock
  */
  PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_CKPER;
  PeriphClkInitStruct.CkperClockSelection = RCC_CLKPSOURCE_HSI;
  if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
